package user;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import model.LyricsPage;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.br.BrazilianAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import control.IndexFields;

public class Searcher {
	private static String DIR_INDEX_PATH = "indexDir";
	
	public static String searchString(String queryString, IndexFields field) {
		String result ="<style type=\"text/css\">" +
				"*{font-family:sans-serif;}a{text-decoration:none;}" +
				".singer{font-family: sans-serif;font-size:11px;font-bold:weight}" +
				".title{font-family: sans-serif;font-size:11px; color:#333}" +
				".description{font-family: sans-serif;font-size:10px}" +
				"</style>\n";
		Analyzer analyzer = new BrazilianAnalyzer(Version.LUCENE_33);
		HashMap<String, Document> docs = new HashMap<String, Document>();
		try {
			
			File idxDirPath = new File(DIR_INDEX_PATH);
			FSDirectory indexDir = null;
			indexDir = FSDirectory.open(idxDirPath);
			
			IndexSearcher idxSearcher = new IndexSearcher(indexDir);
			QueryParser parser;
			if(field != null){
				result += resultQuery(queryString, idxSearcher, field, analyzer, docs);
			}else{
				IndexFields[] fields = IndexFields.values();
				for (int i = 0; i < fields.length; i++) {
					IndexFields indexField = fields[i];
					result += resultQuery(queryString,  idxSearcher, indexField, analyzer, docs);
				}
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println(result + "\n===============");
		return result;
	}

	public static String resultQuery(String queryString, 
			IndexSearcher idxSearcher, IndexFields indexField, Analyzer analyzer, HashMap<String, Document> documents) throws IOException,
			CorruptIndexException {
		String result = "";
		QueryParser parser = new QueryParser(Version.LUCENE_33, indexField.getKey(), analyzer);
		Query query;
		
		try {
			query = parser.parse(queryString);
			TopDocs results = idxSearcher.search(query, 20);
			
			for(ScoreDoc scrDoc : results.scoreDocs){
				Document doc = idxSearcher.doc(scrDoc.doc);
				if (!documents.containsKey(doc.get(IndexFields.TITULO_PAGINA.getKey()))) {
					documents.put(doc.get(IndexFields.TITULO_PAGINA.getKey()), doc);
				}else{
					continue;
				}
				List fields = doc.getFields();
				result +="<p>";
				
				String resultArtista = "",
				resultTitulo = "",
				resultLetra = "",
				resultURL = "",
				resultTituloPagina = "",
				resultConteudo = "";
				
				for (Iterator it = fields.iterator(); it.hasNext();) {
					Fieldable field = (Fieldable) it.next();
					
					if (field.name() == null) continue;
					try {
						switch (IndexFields.fromStringKey(field.name())) {
						case ARTISTA:
							resultArtista = "<span class='singer'>" + doc.get(IndexFields.ARTISTA.getKey()) + "</span> - ";
							break;
						case TITULO:
							resultTitulo = "<span class='title'>" + doc.get(IndexFields.TITULO.getKey()) + "</span><br />";
							break;
						case TITULO_PAGINA:
							resultTituloPagina = "<span class='title'>" + doc.get(IndexFields.TITULO_PAGINA.getKey()) + "</span><br />";
							break;
						case LETRA:
							String lyrics = doc.get(IndexFields.LETRA.getKey());
							int idxQueryL = lyrics.toLowerCase().indexOf(queryString.toLowerCase());
							int idxStartL = 0, idxFinalL = 0;
							
							if(idxQueryL > 100){
								idxStartL = idxQueryL - 100;
							}else{
								idxStartL = 0;
							}
							
							if(lyrics.length() > idxQueryL + 200){
								idxFinalL = idxQueryL + 200;
							}else{
								idxFinalL = lyrics.length();
							}
							resultLetra = "<span class='description'>" + lyrics != null || lyrics != ""?lyrics.substring(idxStartL, idxFinalL):"" + "...</span> <br />";
							break;
						case CONTEUDO:
							String conteudo = doc.get(IndexFields.CONTEUDO.getKey());
							int idxQuery = conteudo.indexOf(queryString);
							int idxStart = 0, idxFinal = 0;
							
							if(idxQuery > 100){
								idxStart = idxQuery - 100;
							}else{
								idxStart = 0;
							}
							
							if(conteudo.length() > idxQuery + 200){
								idxFinal = idxQuery + 200;
							}else{
								idxFinal = conteudo.length();
							}
							
							conteudo = conteudo.substring(idxStart, idxFinal);
							resultConteudo = "<span class='description'>" + conteudo + "...</span><br />";
							break;
						case URL:
							String url = doc.get(IndexFields.URL.getKey());
							if(doc.get("url").length() > 80)
								url = doc.get("url").substring(0, 80);
							resultURL = "<br /><a href=" + doc.get(IndexFields.URL.getKey()) + " class='singer'>" + url + "</a>";
							break;
						default:
							break;
						}
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("ERRRO!");
					}
				}
				result += resultArtista + (resultTitulo != ""? resultTitulo:resultTituloPagina) + (resultLetra != ""? resultLetra:resultConteudo) + resultURL;
				result +="</p>";
			}
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(result);
		return result;
	}
}
